package com.fitnessapp.database;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.json.*;

import android.util.Log;

public class MySqlHelper {
	
	private HttpClient httpClient = new DefaultHttpClient();
	private HttpPost httpPost;
	
	
	public MySqlHelper(String server){
		httpPost = new HttpPost(server);
	}
	
	public List<Map<String,String>> query(String select, String from, String where){
		
		ArrayList<NameValuePair> query = new ArrayList<NameValuePair>();
		
		
		String queryString = "SELECT "+select+" FROM "+ from + " WHERE " + where;
		Log.i("log_tag", queryString);
		query.add(new BasicNameValuePair("query", queryString));
		
		InputStream is = null;
		String result = null;
		List<Map<String,String>> ret = new ArrayList<Map<String,String>>();
		
		try{
			httpPost.setEntity( new UrlEncodedFormEntity(query));
			
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			Log.e("log_tag", "Error in http querry " + e.toString());
		}
		
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			
			String line = null;
			while((line = reader.readLine()) != null){
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		}catch(Exception e){
			 Log.e("log_tag", "Error converting result "+e.toString());
		}
		
		try{	
			Log.i("log_tag", result);
			if(!result.equals("null")){		
						
		        JSONArray jArray = new JSONArray(result);
		        
		        for(int i=0;i<jArray.length();i++){
		        	JSONObject json_data = jArray.getJSONObject(i);
		        	
		        	HashMap<String, String> map = new HashMap<String, String>();
		        	Iterator<?> iter = json_data.keys();
		        	while(iter.hasNext()){	        
		        		String entry = (String)iter.next();
		        		map.put(entry, json_data.getString(entry));
		        	}
		        	
		        	ret.add(map);
		        }
			}
		}catch(JSONException e){
		        Log.e("log_tag", "Error parsing data "+e.toString());
		}
		
		return ret;
	}	

}
